package com.zzl.example.springboottest.util;

import com.zzl.example.springboottest.bean.Student;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
 
public class DynamicAssign {
    public static void assignProperties(Object obj, Map<String, Object> properties) {
        for (Map.Entry<String, Object> entry : properties.entrySet()) {
            String fieldName = entry.getKey();
            Object fieldValue = entry.getValue();
            try {
                Field field = obj.getClass().getDeclaredField(fieldName);
                // 使私有字段可访问
                field.setAccessible(true);
                field.set(obj, fieldValue);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
 
    public static void main(String[] args) {
        Student student = new Student();
        Map<String, Object> properties = new HashMap<>(8);
        properties.put("name", "John Doe");
        properties.put("age", 20);
 
        assignProperties(student, properties);
 
        System.out.println("Name: " + student.getName());
        System.out.println("Age: " + student.getAge());
    }
}